package com.xcjh.module_ad

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.widget.TextView
import com.xcjh.base_lib.base.activity.BaseActivity
import com.xcjh.module_ad.activity.AdMainActivity

/**
 * 在显示应用打开广告之前倒计时的秒数。这模拟了加载应用程序所需的时间。
 */
private const val COUNTER_TIME = 1L

private const val LOG_TAG = "SplashActivity"

/** Splash Activity that inflates splash activity xml. */
@SuppressLint("CustomSplashScreen")
class SplashActivity : BaseActivity() {

    private var secondsRemaining: Long = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.ad_activity_splash)

        // Create a timer so the SplashActivity will be displayed for a fixed amount of time.
        createTimer(COUNTER_TIME)
    }

    /**
     * Create the countdown timer, which counts down to zero and show the app open ad.
     *
     * @param seconds the number of seconds that the timer counts down from
     */
    private fun createTimer(seconds: Long) {
        val counterTextView: TextView = findViewById(R.id.timer)
        val countDownTimer: CountDownTimer = object : CountDownTimer(seconds * 1000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                secondsRemaining = millisUntilFinished / 1000 + 1
                counterTextView.text = "应用程序加载完成： $secondsRemaining"
            }

            override fun onFinish() {
                secondsRemaining = 0
                counterTextView.text = "Done."

                val application = application as? MyApplication

                // If the application is not an instance of MyApplication, log an error message and
                // start the MainActivity without showing the app open ad.
                if (application == null) {
                    Log.e(LOG_TAG, "无法将应用程序转换为 MyApplication")
                    startMainActivity()
                    return
                }
                // Show the app open ad.
                application.showAdIfAvailable(this@SplashActivity) {
                    startMainActivity()
                }
            }
        }
        countDownTimer.start()
    }

    /** Start the MainActivity. */
    fun startMainActivity() {
        startMyActivity<AdMainActivity>()
    }
}